import PageNotFound from "@/ui/pageNotFound.vue";
import { isAuthenticated } from "@/ultils/useAuth";
import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/home/score",
    },
    {
      path: "/home",
      name: "home",
      component: () => import("@/views/HomeView.vue"),
      children: [
        {
          path: "",
          redirect: "/home/score",
        },
        {
          path: "score",
          children: [
            {
              path: "",
              name: "score",
              component: () => import("@/features/score/ScoreList.vue"),
            },
            {
              path: ":id",
              name: "score-edit",
              component: () => import("@/features/score/ScoreEdit.vue"),
            },
            {
              path: "upload",
              name: "score-upload",
              component: () => import("@/features/score/ScoreUpload.vue"),
            },
          ],
        },
        {
          path: "student",
          children: [
            {
              path: "",
              name: "student",
              component: () => import("@/features/student/StudentList.vue"),
            },
            {
              path: ":id",
              name: "student-edit",
              component: () => import("@/features/student/StudentEdit.vue"),
            },
            {
              path: "create",
              name: "student-create",
              component: () => import("@/features/student/StudentCreate.vue"),
            },
          ],
        },
        {
          path: "info",
          name: "info",
          component: () => import("@/features/user/Info.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/features/auth/Login.vue"),
    },
    {
      path: "/signup",
      name: "signup",
      component: () => import("@/features/auth/Signup.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/ui/pageNotFound.vue"),
    },
  ],
});

// 路由守卫
// router.beforeEach(async (to, from, next) => {
//   const isAuthenticated = localStorage.getItem(
//     "sb-gykfmvjuroywaelyraez-auth-token"
//   );
//   if (to.name !== "login" && to.name !== "signup" && !isAuthenticated) {
//     next({ name: "login" });
//   } else {
//     next();
//   }
// });
router.beforeEach(async (to, from, next) => {
  if (to.name !== "login" && to.name !== "signup" && to.name !== "NotFound") {
    const isLogin = await isAuthenticated();
    if (!isLogin) {
      return next({ name: "login" });
    }
  }
  next();
});
export default router;
